#include "FI_ExchRepoData.h"
#include <bondlib/BondCalendar.h>
#include <core/time/time.h>
#include <msgcenter/ExchRepoProcess.h>
#include <qbkernel/include/qb_base.h>
#include <qbprotocol/include/rdProto.h>
#include <qbprotocol/include/SSFIModel.h>
#include <qbtools/message/MessagePoster.h>
#include <uam/ServerTimeMgr.h>

FIExchRepoData::FIExchRepoData()
{
	m_vctOrder = { "GC001", "GC007", "GC014", "GC002", "GC003", "GC004", "GC028", "GC091", "GC182" };

	m_Container.InitData();
}

void FIExchRepoData::clear()
{
	m_Container.ClearPriceData();
	m_Container.Clear();
	m_Container.InitData();
}

const std::vector<std::string>& FIExchRepoData::getOrder()
{
	return m_vctOrder;
}

const std::list<std::string>& FIExchRepoData::getFlash()
{
	return m_lstFlash;
}

const QBExchangeRepoBondContainer& FIExchRepoData::getContainer()
{
	return m_Container;
}

void FIExchRepoData::reqData(MessageReceiver* msgRecv)
{
	static bool reqOnce = false;
	if (reqOnce)return;
	reqOnce = true;

	m_req.m_List.clear();
	for (auto it = m_vctOrder.begin(); it != m_vctOrder.end(); it++)
	{
		const QBExchangeRepoBond* pRepo = m_Container.GetRepoBondByCode(it->c_str());
		if (!pRepo)	continue;

		xMMReq_c unit;
		FIELDCOPY(unit.m_RateKey, pRepo->GetRateKey());
		FIELDCOPY(unit.m_RateID, pRepo->GetID());
		FIELDCOPY(unit.m_ListedMarket, pRepo->GetListedMarket());
		m_req.m_List.push_back(unit);
	}

	qb::SSRequestMsg msg;
	msg.m_pRequest = &m_req;
	msg.m_FuncID = E_FID_QB_MM_EX_PRICE_QUERY_V2;
	MessagePoster poster(&msg, qbmsg::exchangerepo::EncodeFunc);
	poster.send(msgRecv);

	if (!msgRecv)return;
	PushMsgInfo pmi3(E_FID_QB_MM_PRICE_PUSH_V3, "", nullptr);
	msg.m_FuncID = E_FID_QB_MM_PRICE_PUSH_V3;
	msgRecv->registPush(pmi3, &msg, qbmsg::exchangerepo::EncodeFunc);
}

bool FIExchRepoData::onReceive(int32_t funcId, const qb::SSAckMsg& msg)
{
	if (funcId != E_FID_QB_MM_EX_PRICE_QUERY_V2 && funcId != E_FID_QB_MM_PRICE_PUSH_V3)return false;

	xxMMListAck_c* pdata = (xxMMListAck_c*)msg.m_pRet;
	if (!pdata)return false;
	SCOPED_MUTEX(m_lock);
	m_lstFlash.clear();
	for (auto it = pdata->m_List.begin(); it != pdata->m_List.end(); ++it)
	{
		const QBExchangeRepoBond* pRepo = m_Container.GetRepoBond(it->m_RateKey, it->m_ListedMarket);
		if (pRepo)
		{
			if (std::find(m_vctOrder.begin(), m_vctOrder.end(), std::string(pRepo->GetCode())) != m_vctOrder.end())
				m_lstFlash.push_back(pRepo->GetCode());
		}
		m_Container.UpdateData(*it);
	}

	return true;
}
